package com.example.api;

import com.alibaba.fastjson.JSONObject;
import com.example.base.BaseApiService;
import com.example.base.ResponseBase;
import com.example.entity.AppEntity;
import com.example.mapper.AppMapper;
import com.example.utils.BaseRedisService;
import com.example.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class AuthController extends BaseApiService {

    //声明超时时间2小时
    private  final long TimeOut=60*60*2l;
    @Resource
    private AppMapper appMapper;
    @Autowired
    private BaseRedisService redisService;

    @RequestMapping("/getAccessToken")
    public ResponseBase getAccessToken(AppEntity appEntity){
        //1.获取生成对应的appid和appSecret  验证是否有效
        AppEntity app = appMapper.findApp(appEntity);
        if (app==null){
            return setResultError("没有该机构信息，请联系客服。");
        }
        int isFlag = app.getIsFlag();
        if (isFlag==1){
            return setResultError("未对该机构开放权限,请联系客服。");
        }
        //2.删除之前的accessToken，保证第二步与第三步在同一事务中
        String accessToken = TokenUtils.getAccessToken();
        redisService.setString(accessToken,app.getAppId(),TimeOut);//存放数据到redis中
        redisService.getString(accessToken);
        //3.使用Appid和appSecret生成token，保证生成唯一的AccessToken
         String oldAccessToken=app.getAccessToken();
         if (!StringUtils.isEmpty(oldAccessToken)){  //判断accessToken 是否为空，如果不为空 删除之前的token
             redisService.delKey(accessToken);
         }
        //如果不存在accessToken 需要更新数据到数据库
        appMapper.updateAccessToken(accessToken,app.getAppId());
        //4.返回最新的accessToken
        JSONObject data = new JSONObject();
        data.put("accessToken",accessToken);
        return setResultSuccessData(data);
    }


    @RequestMapping("/test")
    public String test(){
        return "测试成功!";
    }
}
